package net.sansi.v3correctserver.util;

import cn.hutool.core.util.StrUtil;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import net.sansi.v3correctserver.exception.ServiceException;

import java.nio.file.Path;

/**
 * Created by Fang
 * create time : 2024/12/13
 * IDE : IntelliJ IDEA
 * <p>
 * 目录工具
 */
@Slf4j
@Getter
public class SpaceUtil {

    private Path path;

    public SpaceUtil(Path path) {
        this.path = path;
        if (!path.toFile().exists()) {
            boolean res = path.toFile().mkdirs();
            if (!res) throw new ServiceException("创建路径失败! {}", path.toUri().toString());
        }
    }

    /**
     * 创建路径
     *
     * @param relativeDir 文件名
     * @return 路径
     */
    public SpaceUtil createDir(String relativeDir, boolean toRelativeDir) {
        Path target = path.resolve(relativeDir);
        if (!target.toFile().exists()) {
            boolean res = target.toFile().mkdirs();
            if (!res) {
                throw new ServiceException("创建路径失败! {}", target);
            }
        }
        if (toRelativeDir) this.path = target;
        return this;
    }

    /**
     * 获取文件路径相对路径
     *
     * @param format 格式
     * @param args   参数
     * @return 文件路径
     */
    public Path resolveFilename(String format, Object... args) {
        return path.resolve(StrUtil.format(format, args));
    }

    /**
     * 获取文件路径相对路径
     *
     * @param relPath 路径
     * @return 文件路径
     */
    public Path resolveFilename(Path relPath) {
        return path.resolve(relPath);
    }

}
